<template>
  <j-modal
    :footer='null'
    :visible='visible'
    :width='1200'
    switchFullscreen
    title='批量添加销售订单明细'
    @cancel='visible = false'
  >
    <!--    搜索栏-->
    <div>
      <div class='search-area'>
        <div style='display: flex'>
          <a-space @keyup.enter='handleSearch'>
            物料名称：
            <a-input v-model='queryParam.materialName' placeholder='请输入物料名称' style='width: 240px'></a-input>
            物料类型：
            <j-dict-select-tag
              v-model='queryParam.materialType'
              dict-code='hf_material_type,material_type_name,id'
              placeholder='请选择物料类型'
              style='width: 160px'
            ></j-dict-select-tag>
            客户：
            <j-search-select-tag
              v-model='queryParam.customId'
              dict='hf_custom,name,id'
              placeholder='请选择客户'
              style='width: 200px'
            ></j-search-select-tag>
          </a-space>
        </div>
        <div>
          <!--    操作栏-->
          <a-space>
            <a-button icon='search' type='primary' @click='handleSearch'>查询</a-button>
            <a-button icon='reload' type='primary' @click='handleReset'>重置</a-button>
            <a-button icon='plus' type='primary' @click='openBatchAddSalePriceList'>查看已添加的数据</a-button>
          </a-space>
        </div>
      </div>
    </div>

    <!--    内容栏-->
    <div>
      <a-button icon='plus' style='margin-bottom: 8px' type='primary' @click='addToBatchAddList'>添加</a-button>
      <a-table
        ref='table'
        :columns='columns'
        :dataSource='dataSource'
        :loading='loading'
        :pagination='ipagination'
        :rowClassName='getRowClassName'
        :rowSelection='{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }'
        :scroll='{ x: true }'
        bordered
        class='j-table-force-nowrap'
        rowKey='id'
        size='middle'
        @change='handleTableChange'
      >
      </a-table>
    </div>

    <HfBatchAddSaleOrderDetailList
      ref='hfBatchAddSaleOrderDetailListRef'
      :sourceId='sourceId'
      :sourceSerial='sourceSerial'
      :table-data='addedDataSource'
      @delete='handleDeleteAddedData'
      @ok='handleOk'
    />
  </j-modal>
</template>

<script>
import '@/assets/less/TableExpand.less'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { Modal } from 'ant-design-vue'
import { getAction } from '@api/manage'
import HfBatchAddPurchasePriceList from '@views/purchase/modules/HfBatchAddPurchasePriceList.vue'
import HfBatchAddSaleOrderDetailList from '@views/sale/modules/HfBatchAddSaleOrderDetailList.vue'

export default {
  name: 'HfBatchAddSaleOrderDetail',
  components: { HfBatchAddSaleOrderDetailList, HfBatchAddPurchasePriceList },
  mixins: [JeecgListMixin],
  data() {
    return {
      visible: false,
      inputNumberWidth: '80px',
      disableMixinCreated: true,
      columns: [
        {
          title: '序号',
          fixed: 'left',
          width: 60,
          align: 'center',
          customRender: (t, r, index) => {
            return index + 1
          }
        },
        {
          title: '物料代码',
          dataIndex: 'materialCode',
          align: 'center',
          width: 120,
          fixed: 'left'
        },
        {
          title: '物料名称',
          dataIndex: 'materialName',
          align: 'center',
          width: 180,
          fixed: 'left'
        },
        {
          title: '规格型号',
          dataIndex: 'sap',
          align: 'center'
        },
        {
          title: '单价',
          dataIndex: 'price',
          align: 'center'
        },
        {
          title: '税率',
          dataIndex: 'tax',
          align: 'center'
        },
        {
          title: '含税单价',
          dataIndex: 'taxPrice',
          align: 'center'
        },
        {
          title: '执行时间',
          dataIndex: 'useTime',
          align: 'center'
        },
        {
          title: '客户',
          dataIndex: 'customId_dictText',
          align: 'center'
        },
        {
          title: '客户品番',
          dataIndex: 'saleCode',
          align: 'center'
        },
        {
          title: '简号',
          dataIndex: 'saleCode1',
          align: 'center'
        },
        {
          title: 'QAD',
          dataIndex: 'qad',
          align: 'center'
        },
        {
          title: '备注',
          dataIndex: 'remark',
          align: 'center'
        }
      ],
      ipagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '15', '20', '25', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
      url: {
        list: '/sale/hfSalePrice/list'
      },
      addedDataSource: [],
      sourceId: '',
      sourceSerial: '',
    }
  },
  computed: {
    // reactiveNameFromParent () {
    //   return this.getReaciveNameFromParent()
    // }

  },
  methods: {
    handleSearch() {
      this.loadData()
    },
    handleReset() {
      this.queryParam = {}
      this.dataSource = []
    },
    addToBatchAddList() {
      // 有没有选中
      if (this.selectionRows.length === 0) {
        this.$message.error('请选择要添加的数据')
        return
      }
      // 筛选重复项
      const repeatRows = this.addedDataSource.filter(selectedItem => this.selectedRowKeys.includes(selectedItem.id))
      const uniqueRows = this.addedDataSource.filter(selectedItem => !this.selectedRowKeys.includes(selectedItem.id))
      if (repeatRows.length > 0) {
        Modal.confirm({
          title: '提示',
          content: h =>
            h('div', [
              h('div', '以下数据已存在,是否覆盖？'),
              h(
                'ul',
                { style: { marginTop: '8px', paddingLeft: '16px' } },
                repeatRows.map(item => h('li', { key: item.id }, item.materialName + '--' + item.price))
              )
            ]),
          width: 700,
          okText: '覆盖',
          cancelText: '只添加不重复的',
          maskClosable: true,
          onOk: () => {
            this.addedDataSource.push(...uniqueRows)
            repeatRows.forEach(repeatItem => {
              const index = this.addedDataSource.findIndex(addedItem => addedItem.id === repeatItem.id)
              if (index !== -1) {
                this.addedDataSource[index] = repeatItem
              }
            })
            this.$message.success('添加成功')
            this.selectedRowKeys = []
          },
          onCancel: () => {
            this.addedDataSource.push(...uniqueRows)
            this.selectedRowKeys = []
            if (uniqueRows.length > 0) {
              this.$message.success('添加成功')
            }
          }
        })
      } else {
        this.addedDataSource.push(...this.selectionRows)
        this.selectedRowKeys = []
        this.$message.success('添加成功')
      }
    },
    openBatchAddSalePriceList() {
      this.$refs.hfBatchAddSaleOrderDetailListRef.visible = true
    },
    loadData(arg) {
      if (!this.url.list) {
        this.$message.error('请设置url.list属性!')
        return
      }
      //加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1
      }
      let param = this.getQueryParams()
      this.loading = true
      param['isDelete'] = 0
      getAction(this.url.list, param)
        .then(res => {
          if (res.success) {
            this.dataSource = res.result.records || res.result
            this.ipagination.total = res.result.total
          } else {
            this.$message.warning(res.message)
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
    handleDeleteAddedData(selectedRowKeys) {
      this.addedDataSource = this.addedDataSource.filter(item => !selectedRowKeys.includes(item.id))
    },
    close() {
      this.visible = false
      this.dataSource = []
      this.addedDataSource = []
      this.$emit('close')
    },
    handleOk() {
      this.close()
      this.$emit('ok')
    },
    // 判断当前行是否已被添加（用于高亮）
    getRowClassName(record) {
      // 防御性检查，确保 addedDataSource 是一个数组
      if (!Array.isArray(this.addedDataSource)) {
        return '' // 如果不是数组，返回空字符串（不应用高亮）
      }
      return this.addedDataSource.some(item => item.id === record.id) ? 'highlight-row' : ''
    }
  }
}
</script>
<style scoped>
@import '~@assets/less/common.less';

.search-area {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  flex-direction: column;
  gap: 10px
}

::v-deep .highlight-row {
  background-color: #64FFDA;
}
</style>
